<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 定时任务与命令目录
 */
namespace app\allwin\controller;
use think\Controller;
use app\allwin\model\MchId;
use app\allwin\model\MchIdQueen;
use app\allwin\model\MchIdUser;
use app\allwin\model\Coupon;
use app\allwin\model\CouponUser;
use app\allwin\widget\Inform;
use app\common\facade\WechatPay;

use think\helper\Time;

class Command extends Controller {

    /**
     * 微信优惠券定时检测
     */  
    public function coupon(){
        //定时检测用户优惠券状态
        $couponuser = CouponUser::where('user_size','<=',0)->whereOr('endtime','<=',Time::today()[0])->update(['is_end' => 1]);
        //定时检测商家优惠券状态
        $coupon     = Coupon::where('num','<=',0)->whereOr('endtime','<=',Time::today()[0])->update(['is_end' => 1]);
        if($coupon || $couponuser){
            return 'SUCCESS';
        }else{
            return 'FINISH';
        }
    }

    /**
     * 微信分账定时任务
     */   
    public function queen(){
        $queen = MchidQueen::where(['is_finish' => 0])->order('id asc')->find();
        if(empty($queen)){
            return 'ALL';
        }
        $transaction_id    = $queen->transaction_id;
        $member_miniapp_id = $queen->member_miniapp_id;
        //读取配置并判断商户模式
        $setting = model('AllwinConfig')->getConfig($member_miniapp_id);
        $sub_mchid = NULL;
        if($setting->is_psp){
            if($queen->store->mch_id){
                $mchid = model('MchId')->getMch($queen->store['mch_id']);
            }else{
                $mchid = model('MchId')->getMch(0,$member_miniapp_id);
            }
            if(empty($mchid)){
                return 'FAIL';
            }
            $sub_mchid = $mchid->mchid;
        }
        $doPay = WechatPay::doPay($member_miniapp_id,false,$sub_mchid);
        //如果金额小于直接结束当前分账
        if($queen->amount <= 0){
            $params['transaction_id'] = $transaction_id;
            $params['out_order_no']   = $queen->out_order_no;
            $params['description']    = '分账已完成';
            $markOrder = $doPay->profit_sharing->markOrderAsFinished($params);
            if($markOrder['return_code'] == 'SUCCESS' && $markOrder['result_code'] == 'SUCCESS'){
                $queen->is_finish = 2;
                $queen->order_id  = $queen->out_order_no;
                $queen->sms       = '成功';
                $queen->save();
            }
            return 'FAIL';
        }
        //读取分账接收方
        $where['member_miniapp_id'] = $member_miniapp_id;
        $where['store_id']          = $queen->store->id;
        if($queen->types == 1){
            $where['mch_id'] = $queen->mch_id;
        }else{
            $where['uid'] = $queen->uid;
        }
        $queen_user = MchIdUser::where($where)->find();
        $data      = [];
        $receivers = [];
        if(empty($queen_user)){
            $data['member_miniapp_id']   = $queen->member_miniapp_id;
            $data['store_id']            = $queen->store->id;
            if($queen->types == 1){
                $mch  = MchId::getMch($queen->mch_id);
                $data['mch_id']                    = $queen->mch_id;
                $data['openid']                    = $mch->mchid;
                $data['receiver']['type']          = 'MERCHANT_ID';
                $data['receiver']['account']       = (string)$mch->mchid;
                $data['receiver']['name']          = $mch->store_name;
                $data['receiver']['relation_type'] = 'STORE_OWNER';
            }else{
                $data['uid']                       = $queen->uid;
                $data['openid']                    = $queen->user['miniapp_uid'];
                $data['receiver']['type']          = $setting->is_psp ? 'PERSONAL_SUB_OPENID': 'PERSONAL_OPENID';
                $data['receiver']['account']       = (string)$queen->user['miniapp_uid'];
                $data['receiver']['relation_type'] = 'USER';
            }
            if($queen->types == 1 && $setting->is_psp){
                if($mchid->mchid == $mch->mchid){
                    $receivers = $data['receiver'];
                    $data['receiver'] = json_encode($receivers);
                    MchIdUser::insert($data);
                    $data['receiver'] = [];
                }
            }
            if(!empty($data['receiver'])){
                $rel = $doPay->profit_sharing->addReceiver($data['receiver']);
                if($rel['return_code'] == 'SUCCESS' && $rel['result_code'] == 'SUCCESS'){
                    $data['receiver'] = $rel['receiver'];
                    MchIdUser::insert($data);
                    $receivers = json_decode($rel['receiver'],true);
                }else{
                    $queen->is_finish = 1;
                    $queen->sms       = empty($rel['return_msg']) ? $rel['err_code_des'] : $rel['return_msg'];
                    $queen->save();
                    return 'FAIL';
                }
            }
        }else{
            $receivers = json_decode($queen_user->receiver,true);
        }
        if(empty($receivers)){
            return 'FAIL';
        }
        //读取上次分账单号
        $order_no = MchidQueen::where(['member_miniapp_id' => $member_miniapp_id,'transaction_id' => $transaction_id,'is_finish' => 2])->order('id desc')->find();
        $out_order_no = empty($order_no) ? $queen->out_order_no : $order_no->order_id;  //分账订单号
        //开始分账
        $receivers['amount']      = $queen->amount;
        $receivers['description'] = $queen->msg;
        $order[] = $receivers;
        $payrel = $doPay->profit_sharing->multiShare($transaction_id,$out_order_no,$order);
        if($payrel['return_code'] == 'SUCCESS'){
            if($payrel['result_code'] == 'SUCCESS'){
                $out_order_no =  $payrel['order_id'];
                $queen->is_finish = 2;
                $queen->order_id  = $out_order_no;
                $queen->sms       = '成功';
            }else{
                if($payrel['err_code'] == 'FREQUENCY_LIMITED' || $payrel['err_code'] == 'ORDER_NOT_READY'){
                    $queen->is_finish = 0;
                }else{
                    $queen->is_finish = 1;
                }
                $queen->sms = $payrel['err_code_des'];
            }
        }else{
            $queen->is_finish = 1;
            $queen->sms     = $payrel['return_msg'];
        }
        $sms = $queen->sms;
        $queen->update_time  =  time();
        $queen->save();
        //查询并结束分账
        $is_end = MchidQueen::where(['member_miniapp_id' => $member_miniapp_id,'transaction_id' => $transaction_id,'is_finish' => 0])->count();
        if($is_end <= 0){
            $params['transaction_id'] = $transaction_id;
            $params['out_order_no']   = $out_order_no;
            $params['description']    = '分账已完成';
            $doPay->profit_sharing->markOrderAsFinished($params);
            return 'END';
        }
        return $sms;
    }

    /**
     * 微信定时模板消息
     */   
    public function inform(){
        $rel = Inform::smsQueue();
        return $rel ? 'SUCCESS' : 'FAIL';
    }
}